#!/bin/bash
#Auto drop ssh failed IP address
#By author jfedu.net 2017
#Define Path variables
SEC_FILE=/var/log/secure
IP_ADDR=`awk '{print $0}'  /var/log/secure|grep -i  "fail"| egrep -o "([0-9]{1,3}\.){3}[0-9]{1,3}" | sort -nr | uniq -c |awk '$1>=1 {print $2}'`
DENY_CONF=/etc/hosts.deny
TM1=`date +%Y%m%d%H%M`
DENY_IP="/tmp/2h_deny_ip.txt"
echo
cat <<EOF
++++++++++++++welcome to use ssh login drop failed ip+++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++------------------------------------++++++++++++++++++
EOF
echo
for ((j=0;j<=2;j++)) ;do echo -n "-";sleep 1 ;done
echo
for i in `echo $IP_ADDR`
do
	cat $DENY_CONF |grep $i >/dev/null 2>&1
	if  [ $? -ne 0 ];then
		grep "$i" $DENY_IP>>/dev/null 2>&1
		if  [ $? -eq 0 ];then
			TM3=`date +%Y%m%d%H%M`
			IP1=`awk -F"[#:]" '/'$i'/ {print $2,$4}' $DENY_IP|awk '{if('$TM3'>=$2+2) print $1}'`
			if [ ! -z $IP1 ];then
				echo "sshd:$IP1:deny #$TM1" >>$DENY_CONF
				sed -i "/$IP1/d"  $DENY_IP 
			fi
		else
    			echo "sshd:$i:deny #$TM1" >>$DENY_CONF
		fi
	fi
done

#Allow IP to access
TM2=`date +%Y%m%d%H%M`
IP2=`awk -F"[#:]" '/sshd/ {print $2,$4}' $DENY_CONF|awk '{if('$TM2'>=$2+2) print $1}'`
for k in `echo $IP2`
do
	echo $k
	sed -i "/$k/d"  $DENY_CONF
	echo "sshd:$k:deny #$TM2" >>$DENY_IP 
done
